// import Category from '@/modal/cateEnum'
import DataItem from '@/modal/dataItem'
// localstrom操作数据
class DataAction {
    dataKey: string;
    memoList!:Array<DataItem>
    constructor(dataKey: string = 'item') {
        // 读取缓存数据
        this.dataKey = dataKey
        this.memoList = this.readData()
    }

    readData():any {
        let strData : string | null = localStorage.getItem(this.dataKey)
        let arrData : any[] = []
        if(strData != null) {
            arrData = JSON.parse(strData)
        }
        return arrData
    }
    // 添加完毕 返回id
    addData (newData: DataItem): number {
        let dataArry = this.memoList
        if(dataArry == null){
            dataArry = []
        }
        let newId = dataArry.length == 0? 1: dataArry[dataArry.length-1].id + 1
        newData.id = newId
        dataArry.push(newData)
        this.saveData(dataArry)
        return newId
        // 数据更新到localstrom中
    }
    saveData(arrData:Array<DataItem>):void {
        let str: string = JSON.stringify(arrData)
        localStorage.setItem(this.dataKey,str)
    }

    // 获取分类
    getCategory(cateId: number): string {
        const arrsName = ['工作', '生活' , '学习']
        return arrsName[cateId]
    } 

    //编辑
    editData(item:DataItem):void {
        let editData: DataItem | undefined = this.memoList.find((ele:any)=>{
            return ele.id == item.id
        })
        if(editData) {
            editData.id = item.id
            editData.title = item.title
            editData.content = item.content
            editData.categoryId = item.categoryId
            this.saveData(this.memoList)
        }
    }

    // 删除
    removeData(id: number): boolean {
        let arr = this.memoList
        const index = arr.findIndex((ele)=>{
            return ele.id === id
        })
        if (index > -1) {
            arr.splice(index,1)
            this.saveData(arr)
            return true
        }
        return false
    }
    

}

export default DataAction